package org.example.mall.admin.service.manage.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.mall.admin.configuration.exception.BaseException;
import org.example.mall.admin.mapper.manage.SysRelationMapper;
import org.example.mall.admin.model.entity.manage.SysRelation;
import org.example.mall.admin.model.enums.manage.SysRelationEnum;
import org.example.mall.admin.service.manage.SysRelationService;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统全局关联表 服务实现类
 * </p>
 *
 * @author hzq
 * @since 2022-01-13
 */
@Service
public class SysRelationServiceImpl extends ServiceImpl<SysRelationMapper, SysRelation> implements SysRelationService {

    @Override
    public void addRelation(Integer fromId, Integer toId, String tbName) {
        addRelation(fromId, Arrays.asList(toId), tbName);
    }

    @Override
    public void addRelation(Integer fromId, List<Integer> toIds, String tbName) {
        hasTbName(tbName);
        if (CollUtil.isEmpty(toIds)) {
            return;
        }
        Set<SysRelation> relations = toIds.stream().map(toId -> {
            SysRelation sysRelation = new SysRelation();
            sysRelation.setFromId(fromId);
            sysRelation.setToId(toId);
            sysRelation.setTbName(tbName);
            return sysRelation;
        }).collect(Collectors.toSet());
        saveBatch(relations);
    }

    @Override
    public void editRelation(Integer fromId, Integer toId, String tbName) {
        editRelation(fromId, Arrays.asList(toId), tbName);
    }

    @Override
    public void editRelation(Integer fromId, List<Integer> toIds, String tbName) {
        delRelationFromId(fromId, tbName);
        addRelation(fromId, toIds, tbName);
    }

    @Override
    public void delRelationFromId(Integer fromId, String tbName) {
        LambdaQueryWrapper<SysRelation> wrapper = Wrappers.<SysRelation>lambdaQuery()
                .eq(SysRelation::getFromId, fromId).eq(SysRelation::getTbName, tbName);
        remove(wrapper);
    }

    @Override
    public void delRelationToId(Integer toId, String tbName) {
        LambdaQueryWrapper<SysRelation> wrapper = Wrappers.<SysRelation>lambdaQuery()
                .eq(SysRelation::getToId, toId).eq(SysRelation::getTbName, tbName);
        remove(wrapper);
    }

    @Override
    public void hasTbName(String tbName) {
        for (SysRelationEnum relationEnum : SysRelationEnum.values()) {
            if (relationEnum.getTbName().equals(tbName)) {
                return;
            }
        }
        throw new BaseException(String.format("不支持全局类型关联tb_name:%s", tbName));
    }
}
